{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# ONNX 序列化\n",
    "\n",
    "参考：[concepts](https://onnx.ai/onnx/intro/concepts.html)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "ONNX 可以类比为一种专门用于数学函数的编程语言。它定义了机器学习模型实现其推理功能所需的所有运算。\n",
    "\n",
    "线性回归可以用以下方式表示："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "onnx_linear_regressor: Already defined.\n"
     ]
    }
   ],
   "source": [
    "from onnxscript import script\n",
    "from onnxscript import opset17 as op\n",
    "\n",
    "@script()\n",
    "def onnx_linear_regressor(X, Wt, Bias):\n",
    "    \"ONNX code for a linear regression\"\n",
    "    return op.MatMul(X, Wt) + Bias"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "模型序列化导出："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "import onnx\n",
    "onnx.save_model(\n",
    "    onnx_linear_regressor.to_model_proto(),\n",
    "    \".temp/linear_regressor.onnx\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](images/linear_regressor-onnx.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这个例子与开发者在 Python 中编写的表达式非常相似。它也可以表示为计算图，展示了逐步变换特征以获得预测的过程。这就是为什么用 ONNX 实现的机器学习模型通常被称为 ONNX 计算图。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "ONNX旨在提供一种通用语言，任何机器学习框架都可以用来描述其模型。第一个场景是使在生产环境中部署机器学习模型更加容易。可以在部署环境中专为这一任务实现和优化一个ONNX解释器（或运行时）。有了ONNX，可以构建一个独特的流程，将模型独立于用于构建模型的学习框架部署到生产中。ONNX实现了一个Python运行时，可用于评估ONNX模型和ONNX操作。这旨在澄清ONNX的语义，并帮助理解和调试ONNX工具及转换器。它不适用于生产环境，性能也不是目标（参见[onnx.reference](https://onnx.ai/onnx/api/reference.html#l-reference-implementation)）。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "xxx",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
